﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Practices.Composite.Events;
using Silverlight.Weblog.Client.CoreBL.Events;
using Silverlight.Weblog.Client.DAL.Events;
using Silverlight.Weblog.Common.IoC;
using Silverlight.Weblog.Server.DAL;

namespace Silverlight.Weblog.UI.UILogic
{
    public class HtmlInitialData : IHtmlInitialData
    {
        public void Initialize()
        {
            SingleBlostPostInit();

            MultipleBlogPostInit();
        }

        private void SingleBlostPostInit()
        {
            string curContent = GetHostHtmlBlock("BlogPost Data");
            if (!string.IsNullOrEmpty(curContent))
            {
                BlogPost blogPostFromHtml =
                    new BlogPost
                    {
                        IsInitializedByHtmlPayload = true,
                        HTML = GetBlockFromHtml("BlogPost Content", curContent),
                        Permlink = GetProperty(curContent, "Permlink"),
                        Title = GetProperty(curContent, "Title")
                    };
                IoC.Get<IEventAggregator>().GetEvent<LoadBlogPostHTMLEvent>().Publish(blogPostFromHtml);
            }
        }

        private void MultipleBlogPostInit()
        {
            string curContent = GetHostHtmlBlock("BlogPosts Data");
            if (!string.IsNullOrEmpty(curContent))
            {
                string[] individualBlogPosts =
                    curContent.Split(new[] { "<!-- BlogPosts Split -->" }, StringSplitOptions.RemoveEmptyEntries);

                List<BlogPost> blogPosts = new List<BlogPost>();
                foreach (string individualBlogPost in individualBlogPosts)
                    blogPosts.Add(new BlogPost
                                      {
                                          IsInitializedByHtmlPayload = true,
                                          HTML = GetBlockFromHtml("BlogPost Content", individualBlogPost),
                                          Permlink = GetProperty(individualBlogPost, "Permlink"),
                                          Title = GetProperty(individualBlogPost, "Title")
                                      });

                IoC.Get<IEventAggregator>().GetEvent<LoadBlogPostsHTMLEvent>().Publish(blogPosts);
            }
        }

        // "<!-- PermlinkStart:" + blogPost.Permlink + " PermlinkEnd-->"
        private string GetProperty(string post, string field)
        {
            string start = "<!-- " + field + "Start:";
            string end = field + "End-->";

            if (!post.Contains(start) || !post.Contains(end))
                return string.Empty;

            int startIndex = post.IndexOf(start);
            int endIndex = post.IndexOf(end);
            int startSubstringIndex = startIndex + start.Length;
            int substringLength = endIndex - startSubstringIndex;

            return post.Substring(startSubstringIndex, substringLength).Trim();
        }

        protected virtual string GetHostHtmlBlock(string BlockName)
        {
            string SilverlightHostHtml = HtmlPage.Document.GetElementById("silverlightControlHost")
                                                          .GetProperty("innerHTML")
                                                          .ToString();

           if (HtmlPage.BrowserInformation.Name == "Microsoft Internet Explorer")
               SilverlightHostHtml = SilverlightHostHtml.Replace(@"&nbsp", @"&nbsp;")
                                                      .Replace(@"&lt", @"&lt;")
                                                      .Replace(@"&gt", @"&gt;")
                                                      .Replace(@"&#160", @"&#160;")
                                                      .Replace(@"&quot", @"&quot;");

            return GetBlockFromHtml(BlockName, SilverlightHostHtml);
        }

        private string GetBlockFromHtml(string BlockName, string Html)
        {
            string BeginDiv = @"<!-- Begin " + BlockName + " -->";
            string EndDiv = "<!-- End " + BlockName + " -->";

            if (Html.IndexOf(BeginDiv) == -1)
                return null;

            int BeginDivIndex = Html.IndexOf(BeginDiv) + BeginDiv.Length;
            int EndDivIndex = Html.IndexOf(EndDiv);
            string BlockContent = Html.Substring(BeginDivIndex, EndDivIndex - BeginDivIndex);
            string BlockContentWithColumnDotCorrection = BlockContent;

            return BlockContentWithColumnDotCorrection;
        }
    }
}
